package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.constant.ResponseCode;
import com.robotserver.orders.constant.ResponseMsg;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.exception.BusinessException;
import com.robotserver.orders.jobs.xxljob.instance.AliPushOrderClient;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.param.biz.TbOrderPullParam;
import com.robotserver.orders.service.*;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.robotserver.orders.vo.biz.PageVO;
import com.robotserver.orders.vo.biz.TbOrderVO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: jianghan
 * @Date: 2019/11/13 17:20
 * @Description:
 */
@Service
public class TbOrderServiceImpl implements TbOrderService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderServiceImpl.class);

    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private AlimmTokensMapper alimmTokensMapper;
    @Autowired
    private TbPayOrderSyncService tbPayOrderSyncService;
    @Autowired
    private TbSettleOrderSyncService tbSettleOrderSyncService;
    @Autowired
    private TbReceivingOrderSyncService tbReceivingOrderSyncService;
    @Autowired
    private TbOrdersMapper tbOrdersMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private TbOrderSyncService tbOrderSyncService;
    @Autowired
    private RatelimitService ratelimitService;

    @Value("${taobao.sdk.url}")
    private String taobaoSdkUrl;
    @Value("${cluster.group} ")
    private String clusterGroup;
    private static int threadRatio = 20;    // 线程比例

    @Async("taskExecutor")
    @Override
    public void syncOrder(TbOrderSyncParam tbOrderSyncParam) {
        int now = DateUtil.getNowTime();
        List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderTimeScope(tbOrderSyncParam.getBegin_time(),tbOrderSyncParam.getEnd_time());
        String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
        String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");

        List<AlimmTokens> alimmTokens = new ArrayList<>();
        if (StringUtils.isNotBlank(tbOrderSyncParam.getAccessToken())){
            AlimmTokens alimmToken = new AlimmTokens();
            alimmToken.setUserId(tbOrderSyncParam.getUserId());
            alimmToken.setUserName(tbOrderSyncParam.getUserName());
            alimmToken.setAccessToken(tbOrderSyncParam.getAccessToken());
            alimmTokens.add(alimmToken);
        }else {
            // 获取联盟数量
            int count = alimmTokensMapper.getCount(now);
            String[] serInfo = clusterGroup.split("_");
            int serCount = Integer.parseInt(serInfo[0]);
            int serInd = Integer.parseInt(serInfo[1]);
            if (count!=0){
                int alimmCount = count/serCount;
                int alimmInd = (alimmCount*serInd);
                if (serInd == serCount-1){
                    alimmCount = alimmCount+(count%serCount);
                }
                alimmTokens = alimmTokensMapper.getTokens(now,alimmInd,alimmCount);
            }
        }

        TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);
        logger.info("alimmTokens is :"+alimmTokens);
        int threadCount = (alimmTokens.size()/threadRatio)+1;
        if (tbOrderSyncParam.getType()==0){         // 支付订单
            String lock = clusterGroup+"_tbpay_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbPayOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lock,tbOrderSyncParam.getOrderScene());
            }
        }else if(tbOrderSyncParam.getType()==1){    // 结算订单
            String lock = clusterGroup+"_tbsettle_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbSettleOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lock,tbOrderSyncParam.getOrderScene());
            }
        }else if(tbOrderSyncParam.getType()==2){    // 确认收货订单
            /*String lock = "tbreceiving_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbReceivingOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lock);
            }*/
        }else {
            String tbpaylock = clusterGroup+"_tbpay_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbPayOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,tbpaylock,tbOrderSyncParam.getOrderScene());
            }


            String tbsettlelock = clusterGroup+"_tbsettle_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbSettleOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,tbsettlelock,tbOrderSyncParam.getOrderScene());
            }

            /*String tbreceivinglock = "tbreceiving_order_lock_"+ IdWorker.getId();
            for (int i=0;i<threadCount;i++){
                tbReceivingOrderSyncService.threadSyncOrder(tbkOrderTimeVOList,alimmTokens,client,tbreceivinglock);
            }*/
        }
    }

    @Override
    public PageVO getOrderList(TbOrderPullParam param) {
        List<TbOrders> list = tbOrdersMapper.getOrderList(param);
        TbOrderVO tbOrderVO = new TbOrderVO();
        tbOrderVO.setRecords(list);
        return tbOrderVO;
    }

    @Override
    public PageVO getOrderListNew(TbOrderPullParam param) {
        List<TbOrders> list = tbOrdersMapper.getOrderListNew(param);
        TbOrderVO tbOrderVO = new TbOrderVO();
        tbOrderVO.setRecords(list);
        return tbOrderVO;
    }

    @Override
    public void invalid(List<TbOrders> orders) {
        if (orders==null || orders.size()==0){
            return ;
        }
        int now = DateUtil.getNowTime();
        for (TbOrders tbOrders:orders){
            TbOrders order = tbOrdersMapper.getByOrderNo(tbOrders.getTradeParentId(),tbOrders.getTradeId());

            if (order==null){
                //logger.info(tbOrders.getTradeParentId()+"::"+tbOrders.getTradeId()+" >> is not exist");
                continue;
            }

            TbOrders updateOrder = new TbOrders();
            updateOrder.setId(order.getId());
            updateOrder.setUpdateTime(now);
            if (tbOrders.getPayPrice()!=null && tbOrders.getPayPrice().intValue()>0){
                updateOrder.setPayPrice(tbOrders.getPayPrice());
            }
            if (tbOrders.getPubShareFee()!=null && tbOrders.getPubShareFee().intValue()>0){
                updateOrder.setPubShareFee(tbOrders.getPubShareFee());
            }

            if(tbOrders.getTkStatus()!=null){
                updateOrder.setTkStatus(tbOrders.getTkStatus());
                if (tbOrders.getTkStatus().intValue()==14){
                    // 结算
                    updateOrder.setBizStatus(1);    // 订单结算
                    updateOrder.setTkEarningTime(now);
                }else{
                    // 失效
                    updateOrder.setBizStatus(2);    // 订单失效
                }
            }else{
                updateOrder.setTkStatus(13);
                updateOrder.setBizStatus(2);    // 订单失效
            }

            tbOrdersMapper.update(updateOrder);
        }
    }

    @Override
    public List<TbOrders> getByOrderId(String orderId) {
        return tbOrdersMapper.getByOrderId(orderId);
    }

    @Override
    public TbOrders getByParAndCliId(String parent_order_no, String child_order_no,Long createdt,String accessToken,String alimmUserId,String alimmUserName) {

        if (createdt!=null && createdt.longValue()>0 && StringUtils.isNotBlank(accessToken)
                && StringUtils.isNotBlank(alimmUserId) && StringUtils.isNotBlank(alimmUserName)){
            String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
            String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");
            TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);

            long begin = createdt.longValue()-1;
            long end = createdt.longValue()+1;

            //判断开始时间是否小于90天前
            Integer now = DateUtil.getNowTime();
            if(begin > (Long.valueOf(now)-7776000)){  //开始时间必须大于90天前，才能拉取订单
                String beginTime = DateFormatUtil.formatDefault(new Date(begin*1000));
                String endTime = DateFormatUtil.formatDefault(new Date(end*1000));
                try {
                    TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();
                    req.setQueryType(1l);    // 创建时间
                    req.setPageSize(100l);   // 100条
                    req.setStartTime(beginTime);
                    req.setEndTime(endTime);
                    req.setJumpType(1l);
                    req.setPageNo(1l);
                    TbkScOrderDetailsGetResponse rsp = client.execute(req, accessToken);
                    // 处理入库
                    if (rsp.getData()!=null){
                        ordersDispose(rsp.getData().getResults(),alimmUserId,alimmUserName);
                    }
                } catch (ApiException e) {
                    logger.error("sync tb pay order err:",e);
                }
            }else{
                logger.error("------根据父订单拉取订单接口失败，开始时间不能小于90天前。-------accessToken="+accessToken+"::alimmUserName="+alimmUserName+"::begintime="+begin+"::endtime="+end);
            }
        }

        return tbOrdersMapper.getByParAndCliId(parent_order_no,child_order_no);
    }


    @Transactional
    @Override
    public void ordersDispose(List<TbkScOrderDetailsGetResponse.PublisherOrderDto> orders,String alimmUserId,String alimmUserName) {
        int now = DateUtil.getNowTime();
        if (orders==null || orders.size()==0){
            return ;
        }
        for (TbkScOrderDetailsGetResponse.PublisherOrderDto order:orders){
            // 查询订单是否存在
            TbOrders tbOrder = tbOrdersMapper.getByOrderNo(order.getTradeParentId(),order.getTradeId());
            if (tbOrder!=null){
                // 修改
                tbOrder.setUpdateTime(now);
                tbOrder.setAdzoneId(order.getAdzoneId());
                tbOrder.setAdzoneName(order.getAdzoneName());
                tbOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                tbOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                tbOrder.setAlimmUserId(alimmUserId);
                tbOrder.setAlimmUserName(alimmUserName);
                tbOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                tbOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                tbOrder.setAlscId(order.getAlscId());
                tbOrder.setAlscPid(order.getAlscPid());
                tbOrder.setLxRid(order.getLxRid());
                tbOrder.setIsLx(order.getIsLx());
                tbOrder.setMarketingType(order.getMarketingType());

                tbOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                tbOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                tbOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                tbOrder.setFlowSource(order.getFlowSource());
                tbOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                tbOrder.setItemCategoryName(order.getItemCategoryName());
                tbOrder.setItemId(order.getItemId());
                tbOrder.setItemImg(order.getItemImg());
                tbOrder.setItemLink(order.getItemLink());
                tbOrder.setItemNum(order.getItemNum());
                tbOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                tbOrder.setItemTitle(order.getItemTitle());

                tbOrder.setOrderType(order.getOrderType());
                tbOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                tbOrder.setPubId(order.getPubId());
                tbOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                tbOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                tbOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                tbOrder.setRefundTag((int) order.getRefundTag().longValue());
                tbOrder.setRelationId(order.getRelationId());
                String sellerNick = order.getSellerNick();
                if(StringUtils.isNotBlank(sellerNick)){
                    tbOrder.setSellerNick(sellerNick.length() > 32 ? sellerNick.substring(0,30) : sellerNick);
                }
                tbOrder.setSellerShopTitle(order.getSellerShopTitle());
                tbOrder.setSiteId(order.getSiteId());
                tbOrder.setSiteName(order.getSiteName());
                tbOrder.setSpecialId(order.getSpecialId());
                tbOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                tbOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                tbOrder.setSubsidyType(order.getSubsidyType());
                tbOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                tbOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                tbOrder.setTerminalType(order.getTerminalType());
                tbOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                tbOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                tbOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                tbOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                tbOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                tbOrder.setTkOrderRole(order.getTkOrderRole());
                tbOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                tbOrder.setTradeId(order.getTradeId());
                tbOrder.setTradeParentId(order.getTradeParentId());
                tbOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                tbOrder.setTkStatus((int)order.getTkStatus().longValue());
                tbOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                tbOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                tbOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                tbOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());

                if (tbOrder.getBizStatus().intValue()==1 && (tbOrder.getTkEarningTime()==null || tbOrder.getTkEarningTime().intValue()==0)){
                    tbOrder.setTkEarningTime(now);
                }

                tbOrdersMapper.update(tbOrder);
            }else {
                // 添加
                logger.info("TB order add :parentId: {},childId: {},tkstatus:{}",new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus()});
                TbOrders newOrder = new TbOrders();
                newOrder.setId(IdWorker.getId());
                newOrder.setCreateTime(now);
                newOrder.setUpdateTime(now);
                newOrder.setAdzoneId(order.getAdzoneId());
                newOrder.setAdzoneName(order.getAdzoneName());
                newOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                newOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                newOrder.setAlimmUserId(alimmUserId);
                newOrder.setAlimmUserName(alimmUserName);
                newOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                newOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                newOrder.setAlscId(order.getAlscId());
                newOrder.setAlscPid(order.getAlscPid());
                newOrder.setLxRid(order.getLxRid());
                newOrder.setIsLx(order.getIsLx());
                newOrder.setMarketingType(order.getMarketingType());

                newOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                newOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                newOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                newOrder.setFlowSource(order.getFlowSource());
                newOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                newOrder.setItemCategoryName(order.getItemCategoryName());
                newOrder.setItemId(order.getItemId());
                newOrder.setItemImg(order.getItemImg());
                newOrder.setItemLink(order.getItemLink());
                newOrder.setItemNum(order.getItemNum());
                newOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                newOrder.setItemTitle(order.getItemTitle());

                newOrder.setOrderType(order.getOrderType());
                newOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                newOrder.setPubId(order.getPubId());
                newOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                newOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                newOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                newOrder.setRefundTag((int) order.getRefundTag().longValue());
                newOrder.setRelationId(order.getRelationId());
                String sellerNick = order.getSellerNick();
                if(StringUtils.isNotBlank(sellerNick)){
                    newOrder.setSellerNick(sellerNick.length() > 32 ? sellerNick.substring(0,30) : sellerNick);
                }
                newOrder.setSellerShopTitle(order.getSellerShopTitle());
                newOrder.setSiteId(order.getSiteId());
                newOrder.setSiteName(order.getSiteName());
                newOrder.setSpecialId(order.getSpecialId());
                newOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                newOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                newOrder.setSubsidyType(order.getSubsidyType());
                newOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                newOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                newOrder.setTerminalType(order.getTerminalType());
                newOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                newOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                newOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                newOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                newOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                newOrder.setTkOrderRole(order.getTkOrderRole());
                newOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                newOrder.setTradeId(order.getTradeId());
                newOrder.setTradeParentId(order.getTradeParentId());
                newOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                newOrder.setTkStatus((int)order.getTkStatus().longValue());
                newOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                newOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                newOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                newOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());
                if (newOrder.getBizStatus().intValue()==1 && (newOrder.getTkEarningTime()==null || newOrder.getTkEarningTime().intValue()==0)){
                    newOrder.setTkEarningTime(now);
                }
                tbOrdersMapper.add(newOrder);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void syncOrder_producer(TbOrderSyncParam tbOrderSyncParam) {
        try {
            //计数位
            //Integer numFlag = 0; //一次生产200个授权之后停顿一秒
            //查询所有有效期内的阿里妈妈tokens
            List<AlimmTokens> alimmTokensList;
            //渠道订单
            if(tbOrderSyncParam.getOrderScene() != null && tbOrderSyncParam.getOrderScene().intValue() == 2){
                //查询所有有效期内的饿了么阿里妈妈tokens
                alimmTokensList = alimmTokensMapper.getAllElmTokens(DateUtil.getNowTime());
            }else{
                //查询所有有效期内的阿里妈妈tokens
                alimmTokensList = alimmTokensMapper.getAllTokens(DateUtil.getNowTime());
            }

            if(alimmTokensList != null){
                //numFlag ++ ;
                //往redis队列中塞阿里妈妈tokens
                for (AlimmTokens alimmTokens : alimmTokensList) {
                    alimmTokens.setBeginTime(tbOrderSyncParam.getBegin_time());
                    alimmTokens.setEndTime(tbOrderSyncParam.getEnd_time());
                    alimmTokens.setTimeType(tbOrderSyncParam.getTimeType());
                    alimmTokens.setOrderScene(tbOrderSyncParam.getOrderScene());
                    alimmTokens.setRedisQueueKey(tbOrderSyncParam.getRedisQueueKey());
                    //对象转成JSON字符串，保存到redis队列中
                    String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                    redisTemplate.opsForList().leftPush(tbOrderSyncParam.getRedisQueueKey(), alimmTokensStr);
                    //logger.info("-------------往redis中推入淘宝联盟的普通账号付款订单tokens------alimmTokensStr=" + alimmTokensStr);
//                    if(numFlag >= 200){
//                        //重置计数位
//                        numFlag = 0;
//                        Thread.sleep(500); //生产200个授权之后，停顿0.5秒
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async("taskExecutor")
    @Override
    public void syncOrder_consumer(TbOrderSyncParam tbOrderSyncParam) {
        String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
        String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");
        TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret,"json", 120000,240000);

        String tb_appkey_dg = sysSettingMapper.getByKey("tb_appkey_dg");
        String tb_appsecret_dg = sysSettingMapper.getByKey("tb_appsecret_dg");
        TaobaoClient client_dg = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey_dg, tb_appsecret_dg,"json", 120000,240000);

        while (true) {
            try {
                //限流-1秒内执行500次
                boolean inRateLimit = ratelimitService.inRateLimit("tbPullOrder-appkey" + tb_appkey,500,1);
                if (inRateLimit){
                    //从redis队列中获取联盟
                    Object alimmTokensObject = redisTemplate.opsForList().rightPop(tbOrderSyncParam.getRedisQueueKey());
                    if (alimmTokensObject != null) {
                        //鉴于client是单例模式，估计初始化项目时，建立连接，创建单例模式
                        //TaobaoClient client = AliPushOrderClient.getTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);
                        //logger.info("tbtoken redis pop:" + alimmTokensObject.toString());
                        AlimmTokens alimmTokens = JSONObject.parseObject(alimmTokensObject.toString(), AlimmTokens.class);
                        //封装分段时间查询参数
                        List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderTimeScope(alimmTokens.getBeginTime(),alimmTokens.getEndTime());
                        if(alimmTokens.getTurnlink() != null && alimmTokens.getTurnlink().intValue() == 1 ){//导购的联盟，需要导购的工具商APP
                            tbOrderSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens,client_dg,alimmTokens.getOrderScene());
                        }else{
                            tbOrderSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens,client,alimmTokens.getOrderScene());
                        }
                    }else{
                        // 没有需要处理的数据了
                        if(CacheKey.tbOrderQueue.equals(tbOrderSyncParam.getRedisQueueKey())){
                            logger.info("-------------------------淘宝常规订单已经消费完成---------------");
                        }else if(CacheKey.tbOrderSldQueue.equals(tbOrderSyncParam.getRedisQueueKey())){
                            logger.info("-------------------------淘宝会员订单已经消费完成---------------");
                        }else if(CacheKey.tbOrderChannelQueue.equals(tbOrderSyncParam.getRedisQueueKey())){
                            logger.info("-------------------------淘宝取单订单已经消费完成---------------");
                        }
                        break;
                    }
                }
                Thread.sleep(5); //5毫秒调用一次
            } catch (Exception e) {
                logger.error("tb redis pop token err:" + e);
                continue;
            }
        }
    }


    private int getStatus(int orderStatus){
        switch (orderStatus){
            case 12:
                return 0; //付款订单
            case 13:
                return 2; //失效订单
            case 14:
                return 1; //结算订单
            case 3:
                return 1; //结算订单
        }
        return 0;
    }


    /**
     * 测试淘宝订单测试方法
     */
    @Async("taskExecutor")
    @Override
    public void syncOrder_downTest(String token){
        String tb_appkey = "33931400";
        String tb_appsecret = "8c0f6dadca25153d1307a1616db10eb1";
        String taobaoSdkUrl = "http://gw.api.taobao.com/router/rest";
        TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);
        TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();
        req.setQueryType(1L);
        req.setPageSize(100L);
        //req.setTkStatus(12l);
        req.setStartTime("2022-10-24 20:09:50");
        req.setEndTime("2022-10-24 20:09:50");
        //req.setJumpType(1l);
        //req.setPageNo(1l);
        //req.setOrderScene(2L);

        try {
            TbkScOrderDetailsGetResponse rsp = client.execute(req, token);

            //限流问题
            if("9100".equals(rsp.getSubCode())){
                logger.error("----淘宝拉取遇到限流问题----token=" + token + "--sub_msg=" + rsp.getSubMsg());
            }else{
                logger.info("----正常下载----token=" + token + "--sub_msg=" + rsp.getSubMsg());
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

}
